<template>
  <div>
    <!-- 微博登录的对话框 -->
    <el-dialog
      title="用户登录"
      :visible.sync="loginDialogFormVisible"
      @close="loginDialogClosed"
    >
      <el-form :model="loginForm" :rules="loginFormRules" ref="loginFormRef">
        <el-form-item
          label="账号"
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input
            v-model="loginForm.username"
            autocomplete="off"
            placeholder="请输入账号(邮箱)"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          :label-width="formLabelWidth"
          prop="password"
        >
          <el-input
            v-model="loginForm.password"
            autocomplete="off"
            placeholder="请输入密码"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-row>
          <el-col :span="12"
            ><div class="reset-wrap" @click="resetLoginForm">
              <div class="reset">重置</div>
            </div></el-col
          ><el-col :span="12"
            ><div class="login-wrap" @click="loginUser">
              <div class="login">登录</div>
            </div></el-col
          ></el-row
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import config from "@/config/index.js";
import { mapState, mapMutations } from "vuex";
export default {
  // 控制登录表单的显示与否
  props: ["showLoginDialog"],
  computed: {
    // 控制登录表单的显示
    loginDialogFormVisible: {
      get() {
        return this.showLoginDialog;
      },
      set(value) {
        this.$emit("loginDialogClosed");
      },
    },
  },
  data() {
    return {
      // 左侧文本的宽度
      formLabelWidth: "100px",
      // 控制登录表单的显示与否
      //   registerDialogFormVisible: true,
      // 登录的表单数据
      loginForm: {
        username: "",
        password: "",
      },
      // 登录表单的验证规则
      loginFormRules: {
        username: [
          { required: true, message: "请输入账号(密码)", trigger: "blur" },
          {
            min: 4,
            max: 20,
            message: "账号长度在 4 到 20 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 4,
            max: 20,
            message: "密码长度在 4 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    ...mapMutations("m_user", [
      "SET_USER_ID",
      "SET_accessToken",
      "SET_refreshToken",
      "SET_tokenType",
      "UPDATE_USER_INFO",
    ]),
    //   用户登录
    loginUser() {
      this.$refs.loginFormRef.validate(async (valid) => {
        if (!valid) return;
        // 发起用户登录的网络请求
        let url = "/oauth/token";
        const res = await this.$http({
          method: "post",
          url: url,
          params: {
            ...this.loginForm,
            client_id: config.themTitle,
            client_secret: config.themTitle,
            grant_type: "password",
          },
        });
        if (res.code != 200) {
          // 隐藏用户登录的对话框
          this.$emit("loginDialogClosed");
          return this.$message("服务器出错了~");
        }
        let { result: data } = res;
        console.log(data);
        // 保存用户的信息
        this.SET_USER_ID(data.user_id);
        this.SET_accessToken(data.access_token);
        this.SET_refreshToken(data.refresh_token);
        this.SET_tokenType(data.token_type);
        this.$message.success("登录成功！");
        // 获取用户信息
        await this.getUserInfo();
        // 隐藏用户登录的对话框
        this.$emit("loginDialogClosed");
      });
    },
    // 获取用户信息
    async getUserInfo() {
      const { code, msg, result } = await this.$http.get(
        "/api/user/user_info/" + localStorage.user_id || ""
      );
      console.log(result);
      if (code != 200) {
        return this.$showMsg({
          msg: "获取用户信息失败！",
          type: "error",
        });
      }

      // 获取用户ip属地
      const res = await this.$http.get("/api/tool/get_ip");
      let code1 = res.code;
      let result1 = res.result;
      if (code1 != 200) {
        return this.$showMsg({
          msg: "获取ip属地失败！",
          type: "error",
        });
      }

      // 添加ip属地
      result.ipAddress = result1.address;
      this.UPDATE_USER_INFO(result);
    },
    // 重置表单
    resetLoginForm() {
      this.$refs.loginFormRef.resetFields();
    },
    // 登录对话框关闭事件
    loginDialogClosed() {
      this.$refs.loginFormRef.resetFields();
      this.$emit("loginDialogClosed");
    },
  },
};
</script>

<style scoped lang="less">
.dialog-footer {
  .login-wrap {
    width: 100%;
    color: white;
    display: flex;
    justify-content: center;
    font-weight: 540;
    .login {
      width: 120px;
      background-color: #ffa00a;
      text-align: center;
      height: 40px;
      line-height: 40px;
      cursor: pointer;
      border-radius: 10px;
    }
  }
  .reset-wrap {
    width: 100%;
    font-weight: 550;
    display: flex;
    justify-content: center;
    .reset {
      height: 40px;
      line-height: 40px;
      cursor: pointer;
      color: #939393;
    }
  }
}
</style>